/*
 * Copyright 2010 Askar Kalykov, oxygene.core@gmail.com
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.oxygenecore.processor.statement;

import com.oxygenecore.processor.*;

/**
 * @author Askar Kalykov
 *         Date: 11.09.2010
 *         Time: 18:18:01
 */
public class ForLoopStatement implements LoopStatement{
    private Statement beforeLoopStatement;
    private Expression<Boolean> conditionStatement;
    private Statement loopStatement;
    private Statement afterLoopStatement;

    public ForLoopStatement(Statement beforeLoopStatement, Expression<Boolean> conditionStatement, Statement loopStatement, Statement afterLoopStatement) {
        if (beforeLoopStatement == null){
            throw new NullPointerException("beforeLoopStatement");
        }
        if (conditionStatement == null){
            throw new NullPointerException("conditionStatement");
        }
        if (loopStatement == null){
            throw new NullPointerException("loopStatement");
        }
        if (afterLoopStatement == null){
            throw new NullPointerException("afterLoopStatement");
        }
        this.beforeLoopStatement = beforeLoopStatement;
        this.conditionStatement = conditionStatement;
        this.loopStatement = loopStatement;
        this.afterLoopStatement = afterLoopStatement;
    }

    public void execute(ExecutionContext executionContext) throws StatementException {
        ExecutionContext forLoopExecutionContext = Configuration.getInstance().createExecutionContext(executionContext);
        beforeLoopStatement.execute(forLoopExecutionContext);
        try {
            while (conditionStatement.getValue(forLoopExecutionContext)){
                ExecutionContext iterationExecutionContext = Configuration.getInstance().createExecutionContext(forLoopExecutionContext);
                loopStatement.execute(iterationExecutionContext);
                afterLoopStatement.execute(forLoopExecutionContext);
            }
        } catch (CalculationException e) {
            throw new StatementException(e, this);
        }

    }
}
